package adong.config;

import adong.interceptor.MyInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.request.async.TimeoutCallableProcessingInterceptor;
import org.springframework.web.servlet.config.annotation.*;

/**
 * @author adong
 */
@EnableWebMvc
@Configuration
@ComponentScan(value = "adong", includeFilters = {
        @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Controller.class})}, useDefaultFilters = false)
public class SpringMvcConfig implements WebMvcConfigurer {


    //视图解析器

    /**
     * 相当于
     * <!--配置文件上传解析器-->
     * <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
     * <property name="defaultEncoding" value="UTF-8"/>
     * <property name="maxUploadSize" value="500000"/>
     * </bean>
     *
     * @param registry
     */
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        //registry.jsp(); 默认从/WEB-INF/下面找, .jps后缀的
        registry.jsp("/WEB-INF/page/", ".jsp");

    }
    //静态资源的访问

    /**
     * <!--SpringMVC无法处理的请求交给tomcat处理-->
     * <mvc:default-servlet-handler/>
     */
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
    //拦截器

    /**
     * <!--配置拦截器-->
     * <mvc:interceptors>
     * <mvc:interceptor>
     * <!--对哪些资源的拦截-->
     * <mvc:mapping path="/**"/>
     * <bean class="com.adong.interceptor.MyInterceptor"></bean>
     * </mvc:interceptor>
     * </mvc:interceptors>
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
    }

    /**
     * 自定义 异步任务执行线程池，解决warnning警告
     * @return
     */
    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.initialize();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(50);
        executor.setThreadNamePrefix("JHW");
        return executor;
    }

    @Bean
    public TimeoutCallableProcessingInterceptor timeoutCallableProcessingInterceptor() {
        return new TimeoutCallableProcessingInterceptor();
    }

    public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
        configurer.setTaskExecutor(threadPoolTaskExecutor());
        configurer.setDefaultTimeout(60 * 1000L);
        configurer.registerCallableInterceptors(timeoutCallableProcessingInterceptor());
    }
}
